package edu.cn.nlsde.tmfst.interfaces;

import edu.cn.nlsde.Utils.IOUtil;

import java.io.BufferedWriter;
import java.io.IOException;
import java.util.*;
import java.util.Map.Entry;

/**
 * Created by dell on 2016/4/26.
 */
public class AbstractLDA {
    public List<List<String>> top_topic_words = null;
    protected int save_step;
    protected String data_path;
    protected double alpha;
    protected double beta;
    protected int iter_num;
    protected int topic_num;
    protected String outputPath;
    protected HashMap<String, Integer> wordMap = new HashMap<>();
    protected HashMap<Integer, String> id2Word = new HashMap<>();
    protected int[][] wordId_of_corpus = null;
    protected int[][] topicId_of_corpus = null;
    protected int[][] word_num_in_topic_word = null;
    protected int[] word_num_in_topic = null;
    protected int[][] word_num_in_doc_topic = null;

    //#############################################################
    protected int[] word_num_in_doc = null;

    //#############################################################

    protected void save_twords(int topWordNum, int saveStep) throws IOException {
        this.top_topic_words = new ArrayList<>();

        BufferedWriter writer = IOUtil.getWriter(this.outputPath + "model-" + saveStep + ".twords");

        for (int topic_index = 0; topic_index < this.word_num_in_topic_word.length; topic_index++) {
            HashMap<Integer, Double> oneLine = new HashMap<>();
            for (int word_id = 0; word_id < this.word_num_in_topic_word[topic_index].length; word_id++) {
                oneLine.put(word_id, ((double) this.word_num_in_topic_word[topic_index][word_id]) / this.word_num_in_topic[topic_index]);
            }
            List<Map.Entry<Integer, Double>> maplist = new ArrayList<>(oneLine.entrySet());

            Collections.sort(maplist, new Comparator<Entry<Integer, Double>>() {
                public int compare(Entry<Integer, Double> o1, Entry<Integer, Double> o2) {
                    return (o2.getValue().compareTo(o1.getValue()));
                }
            });

            writer.write("Topic:" + topic_index + "\n");
            int count = 0;

            List<String> one_Topic = new ArrayList<>();
            for (Map.Entry<Integer, Double> o1 : maplist) {
                writer.write("\t" + this.id2Word.get(o1.getKey()) + "\t:" + o1.getValue() + "\n");
                one_Topic.add(this.id2Word.get(o1.getKey()));
                count++;
                if (count > topWordNum) {
                    break;
                }
            }
            writer.write("\n");
            this.top_topic_words.add(one_Topic);
        }
        writer.close();
    }
}
